import pygame
import sys
import random

# 全局定义
GAME_AREA_HEIGHT = 600  # 游戏区域高度
INFO_AREA_HEIGHT = 50   # 信息区域高度
SCREEN_X = 600
SCREEN_Y = GAME_AREA_HEIGHT + INFO_AREA_HEIGHT  # 总高度 = 游戏区 + 信息区

class Snake(object):
    def __init__(self):
        self.dirction = pygame.K_RIGHT
        self.body = []
        for x in range(5):
            self.addnode()
        
    def addnode(self):
        left, top = (0, 0)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.dirction == pygame.K_LEFT:
            node.left -= 25
        elif self.dirction == pygame.K_RIGHT:
            node.left += 25
        elif self.dirction == pygame.K_UP:
            node.top -= 25
        elif self.dirction == pygame.K_DOWN:
            node.top += 25
        self.body.insert(0, node)
        
    def delnode(self):
        self.body.pop()
        
    def isdead(self):
        # 撞墙 - 只检查游戏区域
        if self.body[0].x not in range(SCREEN_X):
            return True
        if self.body[0].y not in range(GAME_AREA_HEIGHT):
            return True
        # 撞自己
        if self.body[0] in self.body[1:]:
            return True
        return False
        
    def move(self):
        self.addnode()
        self.delnode()
        
    def changedirection(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        if curkey in LR + UD:
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            self.dirction = curkey

class Food:
    def __init__(self):
        self.rect = pygame.Rect(-25, 0, 25, 25)
        
    def remove(self):
        self.rect.x = -25
    
    def set(self, snake_body):
        if self.rect.x == -25:
            # 获取蛇身所有位置
            snake_positions = [(rect.x, rect.y) for rect in snake_body]
            
            # 生成所有可能位置 - 只在游戏区域内
            possible_positions = []
            for x in range(0, SCREEN_X-25, 25):
                for y in range(0, GAME_AREA_HEIGHT-25, 25):
                    if (x, y) not in snake_positions:
                        possible_positions.append((x, y))
            
            if possible_positions:
                pos = random.choice(possible_positions)
                self.rect.x, self.rect.y = pos

def show_text(screen, pos, text, color, font_bold=False, font_size=25, font_italic=False):   
    cur_font = pygame.font.SysFont("Arial", font_size)  # 使用更通用的字体
    cur_font.set_bold(font_bold)  
    cur_font.set_italic(font_italic)  
    text_fmt = cur_font.render(text, True, color)  
    screen.blit(text_fmt, pos)

def main():
    pygame.init()
    screen_size = (SCREEN_X, SCREEN_Y)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('Snake')
    clock = pygame.time.Clock()
    scores = 0
    isdead = False
    paused = False
    
    snake = Snake()
    food = Food()
    
    def reset_game():
        nonlocal snake, food, scores, isdead, paused
        snake = Snake()
        food = Food()
        scores = 0
        isdead = False
        paused = False
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                # 暂停/继续功能 (按P键)
                if event.key == pygame.K_p:
                    paused = not paused
                
                # 方向控制（游戏未暂停且未死亡时有效）
                if not paused and not isdead:
                    snake.changedirection(event.key)
                
                # 重新开始（死亡时按空格）
                if event.key == pygame.K_SPACE and isdead:
                    reset_game()
        
        # 绘制游戏界面
        # 1. 游戏区域背景（蛇活动区域）
        game_area = pygame.Rect(0, 0, SCREEN_X, GAME_AREA_HEIGHT)
        pygame.draw.rect(screen, (255, 255, 255), game_area)
        
        # 2. 信息区域背景（分数和暂停提示）
        info_area = pygame.Rect(0, GAME_AREA_HEIGHT, SCREEN_X, INFO_AREA_HEIGHT)
        pygame.draw.rect(screen, (240, 240, 240), info_area)
        pygame.draw.line(screen, (180, 180, 180), (0, GAME_AREA_HEIGHT), (SCREEN_X, GAME_AREA_HEIGHT), 2)
        
        # 画网格背景（只在游戏区域内）
        for x in range(0, SCREEN_X, 25):
            pygame.draw.line(screen, (220, 220, 220), (x, 0), (x, GAME_AREA_HEIGHT))
        for y in range(0, GAME_AREA_HEIGHT, 25):
            pygame.draw.line(screen, (220, 220, 220), (0, y), (SCREEN_X, y))
        
        # 只有在未暂停且未死亡时才更新游戏状态
        if not paused and not isdead:
            # 移动蛇
            snake.move()
            
            # 食物处理
            if food.rect.colliderect(snake.body[0]):
                scores += 10
                food.remove()
                snake.addnode()
            
            # 检查死亡
            isdead = snake.isdead()
        
        # 画蛇身（只在游戏区域内）
        for rect in snake.body:
            pygame.draw.rect(screen, (20, 220, 39), rect, 0)
        
        # 食物投递（只在游戏区域内）
        food.set(snake.body)
        pygame.draw.rect(screen, (136, 0, 21), food.rect, 0)
        
        # 显示死亡文字（在游戏区域内居中）
        if isdead:
            show_text(screen, (SCREEN_X//2 - 150, GAME_AREA_HEIGHT//2 - 50), 'YOU DEAD!', (227, 29, 18), False, 60)
            show_text(screen, (SCREEN_X//2 - 180, GAME_AREA_HEIGHT//2 + 20), 'Press SPACE to restart', (0, 0, 0), False, 30)
        
        # 显示暂停文字（在游戏区域内居中）
        if paused and not isdead:
            show_text(screen, (SCREEN_X//2 - 70, GAME_AREA_HEIGHT//2 - 30), 'PAUSED', (0, 0, 200), False, 60)
        
        # ===== 信息区域显示 =====
        # 使用统一的字体样式（大小25，颜色黑色）
        info_font_size = 25
        info_color = (0, 0, 0)
        
        # 1. 显示分数（左侧）
        show_text(screen, (20, GAME_AREA_HEIGHT + 15), f'SCORE: {scores}', info_color, False, info_font_size)
        
        # 2. 显示长度（中间）
        show_text(screen, (SCREEN_X//2 - 50, GAME_AREA_HEIGHT + 15), f'LENGTH: {len(snake.body)}', info_color, False, info_font_size)
        
        # 3. 显示暂停状态（右侧）
        pause_text = "PAUSED (P)" if paused else "PLAYING (P)"
        show_text(screen, (SCREEN_X - 180, GAME_AREA_HEIGHT + 15), pause_text, info_color, False, info_font_size)
        
        pygame.display.update()
        
        # 动态速度控制（仅在游戏进行中）
        if not paused and not isdead:
            speed = 10 + len(snake.body) // 3
            clock.tick(min(speed, 20))
        else:
            # 暂停时保持较低帧率以减少CPU占用
            clock.tick(5)

if __name__ == '__main__':
    main()